package com.htu.study.service.serviceImpl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.htu.study.mapper.UserMapper;
import com.htu.study.pojo.User;
import com.htu.study.service.user.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public Map<String, String> register(String user_name, String user_password, String user_confirmed_password) {

        Map<String, String> map = new HashMap<>();

        if(user_name == null) {
            map.put("error_message", "用户名不能为空");
        }
        if(user_password == null || user_password.length() == 0) {
            map.put("error_message", "密码不能为空");
            return map;
        }
        if(user_confirmed_password==null || user_confirmed_password.length() == 0){
            map.put("error_message","第二次密码不能为空");
            return map;
        }

        if (user_name != null) {
            user_name = user_name.trim();
        }
        if (user_name != null && user_name.length() == 0) {
            map.put("error_message", "用户名不能为空");
            return map;
        }

        if (user_name != null && user_name.length() > 20) {
            map.put("error_message", "用户名长度不能大于20");
            return map;
        }
        if(user_password.length() > 20 || user_confirmed_password.length() > 20) {
            map.put("error_message", "密码长度不能大于20");
            return map;
        }
        if(!user_password.equals(user_confirmed_password)) {
            map.put("error_message", "两次输入的密码不一致");
            return map;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_name", user_name);
        List<User> users = userMapper.selectList(queryWrapper);
        if(!users.isEmpty()) {
            map.put("error_message", "用户名已存在");
            return map;
        }
        String user_photo="https://picx.zhimg.com/80/v2-80cefd61105a80107c5afd96c4eb7344_720w.webp?source=1def8aca";
        String encodedPassword = passwordEncoder.encode(user_password);//密码加密
        User user = new User(null, user_name, encodedPassword,user_photo,"学生",new Date());
        userMapper.insert(user);
        map.put("error_message", "success");
        return map;
    }
}
